 import React, { PureComponent } from 'react'
 import { withRouter } from "react-router-dom";
 import { connect } from "react-redux";
 import { Select, Button, Dropdown, Menu, Modal } from 'antd'
 import ParamsInput from "@common/presentational/ParamsInput";
 import { COUPON_NAME_TYPE, COUPON_STATUS, COUPON_STATUS_MAP } from '@constants/ActivityListMap'
 import { getAllCoupons, getCouponDetail, pauseCoupons, resumeCoupons, publishCoupons } from '@sagas/marketing'
 import { createCustomizeMiniCode } from "@sagas/thirdparty";
 import marketArrayParams from '@utils/marketArrayParams'
 import DropdownMenu from "@common/presentational/DropdownMenu";
 import {getQuery, handleQueryEqual, setQuery} from "@utils/setUrlQuery";
 import CustomizeTableProvide, { CustomizeTable, CustomizeTablePagination } from "@common/presentational/CustomizeTable";
 import {
    setHeaderBreadCrumbInfo
} from "@sagas/common";
import {priceFenToYuan, priceYuanToFen} from "@utils/priceConversion";
import CouponStatsModal from '@components/marketing/modal/CouponStatsModal'
 import {MiniCodeModal} from "@common/presentational/MiniCodeModal";
 import BilinIcon from "@common/presentational/BilinIcon";

@withRouter
@connect(({ marketing }) => ({
    allCoupons: marketing.allCoupons,
}), {
        setHeaderBreadCrumbInfo,
        getAllCoupons,
        getCouponDetail,
        pauseCoupons,
        resumeCoupons,
        publishCoupons,
        createCustomizeMiniCode
    }
)
 class MarketingCouponPage extends PureComponent {
    constructor(props) {
        super(props);
        const {
            status = '',
            type = '',
            keyword = '',
        } = getQuery(props.history)
        this.state = {
            status,
            type,
            keyword
        }

        this.tableRef = React.createRef()
        this.couponStatsModalRef = React.createRef()
        this.miniCodeModalRef = React.createRef()
        this.getTableInfo = this.getTableInfo.bind(this)
        this.showQrCode = this.showQrCode.bind(this)
        this.modifyCoupon = this.modifyCoupon.bind(this)
        this.resumeCoupon = this.resumeCoupon.bind(this)
        this.pauseCoupon = this.pauseCoupon.bind(this)

        this.paginationInfo = {}
        this.columns = [{
            dataIndex: 'name',
            key: 'name',
            title:'优惠券名称',
            width: 180,
            render: (text, record) => record.self.name
        },{
            dataIndex: 'offer_type',
            key: 'offer_type',
            title:'类型',
            width: 80,
            render: (text, record) => COUPON_NAME_TYPE[record.self.offer_type]
        },{
            dataIndex: 'content',
            key: 'content',
            title:'优惠券内容',
            render:(text, record) =>{
                if(record.self.offer_type === 'quota_cut'){
                    return `${record.self.quota? `满${priceFenToYuan(record.self.quota)}元` : ''} 减${priceFenToYuan(record.self.price)}元`
                }
                if(record.self.offer_type === 'discount'){
                    return `${record.self.quota? `满${priceFenToYuan(record.self.quota)}元` : ''} 打${record.self.price/10}折 ${record.self.off_maximum? `最多优惠${priceFenToYuan(record.self.off_maximum)}元` : ''}`
                }
            }
        },{
            dataIndex: 'coupon_status',
            key: 'coupon_status',
            title:'状态',
            width: 80,
            render: (text, record)=>COUPON_STATUS[record.self.coupon_status]
        },{
            dataIndex: 'cnt',
            key: 'cnt',
            title:'数量',
            width: 250,
            render:(text, record) =>{
                return `总量：${record.stat.distributed_cnt} 已领取：${record.stat.got_cnt} 已使用：${record.stat.use_cnt}`
            }
        },{
            dataIndex: 'options',
            key: 'options',
            title:'操作',
            render: (text, record) => {
                let dropList = [{
                    key: 'qrCode',
                    name: '领券二维码',
                },{
                    key: 'modify',
                    name: '编辑',
                }];
                if(record.self.coupon_status === 'paused'){
                    dropList.push({
                        key: 'resume',
                        name: '生效',
                    })
                }
                if(record.self.coupon_status === 'published'){
                    dropList.push({
                        key: 'pause',
                        name: '失效',
                    })
                }
                return (
                    <div className="flex-vertical-center">
                        {record.self.coupon_status === 'draft' && <div onClick={this.publishCoupon.bind(this,record)} className="mgr-8 ft-hover">发布</div>}
                        <div onClick={this.distribution.bind(this,record)} className="mgr-8 ft-hover">投放</div>
                        <div onClick={this.showStat.bind(this,record)} className="mgr-8 ft-hover">数据</div>
                        <DropdownMenu
                            dropdownList={dropList}
                            onClick={this.handleRowOperation.bind(this, record)}
                        >
                            <div className="ft-hover">更多</div>
                        </DropdownMenu>
                    </div>
                )
            }
        } ]
    }

    distribution(record){
        const { history } = this.props
        history.push({
            pathname: `/marketing/coupon/distribution/${record.self.id}`,
        })
    }

    publishCoupon(record){
        const { publishCoupons } = this.props
        const that = this
        Modal.confirm({
            title: '确认发布？',
            icon: null,
            onOk: ()=>{
                publishCoupons({
                    id: record.self.id
                }, () => {
                    that.getTableInfo()
                })
            }
        })
    }
    
    resumeCoupon(record){
        const { resumeCoupons } = this.props
        const that = this
        Modal.confirm({
            title: '是否确认生效',
            icon: null,
            onOk: ()=>{
                resumeCoupons({
                    id: record.self.id
                }, () => {
                    that.getTableInfo()
                })
            }
        })
    }

    pauseCoupon(record){
        const { pauseCoupons } = this.props
        const that = this
        Modal.confirm({
            title: '是否确认失效',
            icon: null,
            // content:<></>,
            onOk: ()=>{
                pauseCoupons({
                    id: record.self.id
                }, () => {
                    that.getTableInfo()
                })
            }
        })
    }

    modifyCoupon(record){
        const { getCouponDetail, history } = this.props
        getCouponDetail({
            id: record.self.id
        }, (res) => {
            history.push({
                pathname: `/marketing/coupon/${record.self.offer_type}/modify/${record.self.id}`,
                state: {
                    ...res.coupon
                }
            })
        })
    }

    showStat(record){
        this.couponStatsModalRef.current?.show({
            ...record.stat
        })
    }

    showQrCode(record){
        this.props.createCustomizeMiniCode({
            path: 'pages/activity/index',
            query: `type=${record.self.offer_type}&id=${record.self.id}`,
            codeKey: record.self.id
        }, () => {
            this.miniCodeModalRef.current?.show({codeKey: record.self.id})
        })
    }

    handleRowOperation(record, type) {
        switch (type) {
            case 'resume':
                this.resumeCoupon(record)
                break;
            case 'pause':
                this.pauseCoupon(record)
                break;
            case 'modify':
                this.modifyCoupon(record)
                break;
            case 'qrCode':
                this.showQrCode(record)
                break;
            default:
                break;
        }
    }

    componentDidMount(){
        this.props.setHeaderBreadCrumbInfo([{
            text: '营销',
            link: '/marketing',
        },{
            text: '优惠券',
            link: '',
        }])
    }

    componentWillUnmount () {
        this.props.setHeaderBreadCrumbInfo(null)
    }

    handleValueChange (key, value) {
        this.setState({
            [key]: value
        }, this.initTable)
    }

    getTableInfo ({ current, pageSize } = this.paginationInfo) {
        this.paginationInfo = { current, pageSize }
        const { status,type, keyword } = this.state
        const params = {
            pageNo: current,
            pageSize
        }
        if(status){
            params.coupon_statuses = marketArrayParams(status)
        }
        if(type){
            params.offer_types = marketArrayParams(type)
        }
        if(keyword){
            params.keyword = keyword
        }
        this.props.getAllCoupons(params)
        this.setUrlQuery()
    }

    initTable () {
        this.tableRef.current?.initPage()
    }

    setUrlQuery () {
        const { status, type, keyword } = this.state
        const { history } = this.props
        let params = { status, type, keyword }
        handleQueryEqual(params, history) || setQuery(params, history)
    }

    handleOperationClick(key){
        const { history } = this.props
        history.push(`/marketing/coupon/${key}/create`)
    }
 
     render() {
         const { status, type, keyword } = this.state
         const { allCoupons } = this.props
         return (
             <div className='marketing-page table-scroll-container'>
                <div className="table-params page-params flex-row-between mgb-16">
                    <div className="flex-vertical-center">
                        <Dropdown
                            overlay={(
                                <Menu>
                                    <Menu.Item onClick={this.handleOperationClick.bind(this,'quota_cut')} key="quota_cut">满减券</Menu.Item>
                                    <Menu.Item onClick={this.handleOperationClick.bind(this,'discount')} key="discount">折扣券</Menu.Item>
                                </Menu>
                            )}
                            trigger={['click']}
                        >
                            <Button type="primary" className="button-small mgr-16"><BilinIcon type="plus" className="ft-18 mgr-8"/>新建优惠券</Button>
                        </Dropdown>
                    </div>
                    <div className="flex-vertical-center">
                    <Select
                        style={{width: '140px'}}
                        onChange={this.handleValueChange.bind(this, 'status')}
                        value={status}
                    >
                        <Select.Option key="" value="">全部状态</Select.Option>
                        {COUPON_STATUS_MAP.map(item=>{
                            return(<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>)
                        })}
                    </Select>
                    <Select
                        className="mgl-16"
                        style={{width: '140px'}}
                        onChange={this.handleValueChange.bind(this, 'type')}
                        value={type}
                    >
                        <Select.Option key="" value="">全部类型</Select.Option>
                        <Select.Option key="discount" value="discount">折扣券</Select.Option>
                        <Select.Option key="quota_cut" value="quota_cut">满减券</Select.Option>
                    </Select>
                    <ParamsInput
                        className="mgl-16"
                        style={{width: '140px'}}
                        value={keyword}
                        onChange={this.handleValueChange.bind(this, 'keyword')}
                        placeholder="优惠券名称"
                    />
                    </div>
                </div>
                <CustomizeTableProvide ref={this.tableRef} tableKey="couponList" onChange={this.getTableInfo}>
                    <div className="table-list">
                        <CustomizeTable
                            columns={this.columns}
                            dataSource={allCoupons.rows || []}
                        />
                    </div>
                    <div className="table-pagination">
                        <CustomizeTablePagination
                            total={allCoupons.total}
                        />
                    </div>
                </CustomizeTableProvide>
                <CouponStatsModal ref={this.couponStatsModalRef} />
                <MiniCodeModal ref={this.miniCodeModalRef} />
             </div>
         )
     }
 }
 
 export default MarketingCouponPage